﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WorkFlowBLL;

namespace QLCF.Forms
{
    public partial class frmTableService : Form
    {
        public int permission = 0;
        public frmTableService()
        {
            InitializeComponent();
            permission = CtrAdmin.GetPermission(Program.UserEntity.Permission, Config.Enum.Function.frmTableService);
            DisableBillOnTable(true);
        }


        private void loadCate()
        {
            TreeNode node1 = new TreeNode();
            node1.Text = "Tất cả";
            node1.Tag = -1;
            node1.ImageIndex = 1;
            node1.SelectedImageIndex = 1;
            treeViewCate.Nodes.Add(node1);
            CtrCategory ctrC = new CtrCategory();
            var items = ctrC.GetListCategory();
            foreach (var item in items)
            {
                TreeNode node = new TreeNode();
                node.Text = item.CategoryName;
                node.Tag = item.CategoryID;
                node.ImageIndex = 0;
                treeViewCate.Nodes.Add(node);
            }
        }

        private void frmTableService_Load(object sender, EventArgs e)
        {
            tabControl.Name = "tabRange";

            CtrTable ctrT = new CtrTable();
            var lastNameList = ctrT.RangeGetByStatus(1);
            foreach (var item in lastNameList)
            {

                TabPage tabPage = new TabPage();
                tabPage.Tag = item.RangeID;
                tabPage.Name = "tabPage" + item.RangeID;
                tabPage.Text = item.RangeName;

                ListView lv1 = new ListView();
                lv1.Name = "listViewTableOn" + item.RangeID;
                lv1.Dock = DockStyle.Fill;
                lv1.LargeImageList = imgListTable;
                var tables = ctrT.TableGetOn(item.RangeID);
                foreach (var table in tables)
                {
                    ListViewItem ListViewItem1 = new ListViewItem(table.TableName);
                    ListViewItem1.ImageIndex = table.BillID.HasValue ? 1 : 0;
                    ListViewItem1.Tag = table.TableID.ToString() + "+" + (table.BillID ?? -1).ToString();
                    lv1.Items.Add(ListViewItem1);
                }
                lv1.MultiSelect = false;
                lv1.View = View.LargeIcon;
                lv1.ContextMenuStrip = contextMenuStripOnTable;
                lv1.BorderStyle = BorderStyle.None;
                lv1.SelectedIndexChanged += new EventHandler(lv1_SelectedIndexChanged);
                tabPage.Controls.Add(lv1);


                tabControl.Controls.Add(tabPage);
            }
            this.splitContainer1.Panel1.Controls.Add(tabControl);


            loadCate();
            treeViewCate.SelectedNode = treeViewCate.Nodes[0];

            tabControl.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom;
            // Why isn't there a convenient enum value for 'All'? 
            tabControl.Location = new Point(0, 10);
            tabControl.Size = new Size(tabControl.Parent.ClientSize.Width
             , tabControl.Parent.ClientSize.Height - (0 + 10)
             );
            timer1.Interval = 1;
            timer1.Start();
            listViewUsedPro.Columns[listViewUsedPro.Columns.Count - 1].Width = -2;
            listViewProduct.Columns[listViewProduct.Columns.Count - 1].Width = -2;
        }
        private int billID = -1;
        private int tableID = -1;
        private void lv1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListView lv1 = (ListView)sender;
            if (lv1.SelectedItems.Count <= 0)
                return;
            foreach (ListViewItem table in lv1.Items)
            {
                if (table.BackColor != Color.Transparent)
                    table.BackColor = Color.Transparent;
            }
            lv1.SelectedItems[0].BackColor = Color.FromArgb(220, 220, 220);
            tableID = Convert.ToInt32(lv1.SelectedItems[0].Tag.ToString().Split('+')[0]);
            billID = Convert.ToInt32(lv1.SelectedItems[0].Tag.ToString().Split('+')[1]);
            CtrProduct ctrP = new CtrProduct();
            var billInfoC = ctrP.BillGetInfoCommon(billID);
            if (billInfoC != null)
            {
                lblTableName.Text = billInfoC.TableName;
                lblTimeOpen.Text = "Giờ mở: " + billInfoC.StartTime.ToShortTimeString();
                lblDateOpen.Text = "Ngày: " + billInfoC.StartTime.ToShortDateString();
            }
            else
            {
                lblTableName.Text = lv1.SelectedItems[0].Text;
                lblTimeOpen.Text = "Giờ mở: " + DateTime.Now.ToShortTimeString();
                lblDateOpen.Text = "Ngày: " + DateTime.Now.ToShortDateString();
                lblSumMoney.Text = "0 VNĐ";
                numService.Value = 0;
                numericPromotion.Value = 0;
                lblTotalMoney.Text = "0 VNĐ";
            }
            RefreshBill();

            if ((permission & (int)Config.Enum.Permission.Add) != (int)Config.Enum.Permission.Add)
                btnAdd.Enabled = false;

            if ((permission & (int)Config.Enum.Permission.Edit) != (int)Config.Enum.Permission.Edit)
            {
                toolStripButtonSetQuantity.Enabled = false;
                //toolStripButtonChangePrice.Enabled = false;
                toolStripButtonUpdateDescription.Enabled = false;
                numericPromotion.Enabled = false;
                numService.Enabled = false;
            }

            if ((permission & (int)Config.Enum.Permission.Delete) != (int)Config.Enum.Permission.Delete)
            {
                btnDelete.Enabled = false;                
            }
        }


        private void timer1_Tick(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
            timer1.Stop();
        }

        private void contextMenuStripOnTable_Opening(object sender, CancelEventArgs e)
        {
            try
            {
                var control1 = (ListView)contextMenuStripOnTable.SourceControl;
                if (control1.SelectedItems.Count != 1)
                {
                    openTableToolStripMenuItem.Enabled = false;
                    paymentToolStripMenuItem.Enabled = false;
                    moveToolStripMenuItem.Enabled = false;
                    grossToolStripMenuItem.Enabled = false;
                    refreshToolStripMenuItem.Enabled = true;
                    cancelBillToolStripMenuItem.Enabled = false;
                }
                else
                {
                    ListViewItem lvItem1 = control1.SelectedItems[0];
                    if (lvItem1.ImageIndex == 1)
                    {
                        openTableToolStripMenuItem.Enabled = false;
                        moveToolStripMenuItem.Enabled = true;
                        paymentToolStripMenuItem.Enabled = true;
                        grossToolStripMenuItem.Enabled = true;
                        cancelBillToolStripMenuItem.Enabled = true;
                    }
                    else
                    {
                        openTableToolStripMenuItem.Enabled = true;
                        moveToolStripMenuItem.Enabled = false;
                        paymentToolStripMenuItem.Enabled = false;
                        grossToolStripMenuItem.Enabled = false;
                        cancelBillToolStripMenuItem.Enabled = false;
                    }
                    refreshToolStripMenuItem.Enabled = true;

                    if ((permission & (int)Config.Enum.Permission.Add) != (int)Config.Enum.Permission.Add)
                        openTableToolStripMenuItem.Enabled = false;

                    if ((permission & (int)Config.Enum.Permission.Edit) != (int)Config.Enum.Permission.Edit)
                    {
                        moveToolStripMenuItem.Enabled = false;
                        grossToolStripMenuItem.Enabled = false;
                        
                    }

                    if ((permission & (int)Config.Enum.Permission.Delete) != (int)Config.Enum.Permission.Delete)
                    {
                        cancelBillToolStripMenuItem.Enabled = false;
                    }
                }
            }
            catch
            {
                openTableToolStripMenuItem.Enabled = false;
                paymentToolStripMenuItem.Enabled = false;
                moveToolStripMenuItem.Enabled = false;
                grossToolStripMenuItem.Enabled = false;
                refreshToolStripMenuItem.Enabled = true;
                cancelBillToolStripMenuItem.Enabled = false;
            }
        }

        private void treeViewCate_AfterSelect(object sender, TreeViewEventArgs e)
        {
            listViewProduct.Items.Clear();
            var cateID = Convert.ToInt32(e.Node.Tag);
            CtrProduct ctrT = new CtrProduct();
            var items = ctrT.ProductGetByCate(cateID, 1, -1);
            foreach (var item in items)
            {
                ListViewItem item1 = new ListViewItem(item.ProductName);
                item1.SubItems.Add(item.Unit);
                item1.SubItems.Add(item.PriceName);
                item1.Tag = item.ProductID;
                listViewProduct.Items.Add(item1);
            }
            e.Node.BackColor = Color.FromArgb(220, 220, 220);
        }

        private void txtKeyWord_KeyDown(object sender, KeyEventArgs e)
        {
            listViewProduct.Items.Clear();
            var cateID = Convert.ToInt32(treeViewCate.SelectedNode.Tag);
            CtrProduct ctrT = new CtrProduct();
            var items = ctrT.ProductGetByCate(txtKeyWord.Text, cateID, -1, -1, -1);
            foreach (var item in items)
            {
                ListViewItem item1 = new ListViewItem(item.ProductName);
                item1.SubItems.Add(item.Unit);
                item1.SubItems.Add(item.PriceName);
                item1.Tag = item.ProductID;
                listViewProduct.Items.Add(item1);
            }
        }

        private void treeViewCate_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            if (treeViewCate.SelectedNode != null)
                treeViewCate.SelectedNode.BackColor = Color.Transparent;
        }

        private void listViewUsedPro_Resize(object sender, EventArgs e)
        {
            listViewUsedPro.Columns[listViewUsedPro.Columns.Count - 1].Width = -2;
        }

        private void listViewProduct_Resize(object sender, EventArgs e)
        {
            listViewProduct.Columns[listViewProduct.Columns.Count - 1].Width = -2;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (numQuantity.Value <= 0)
            {
                MessageBox.Show("Số lượng phải >0");
                numQuantity.Focus();
                return;
                
            }
            if (billID <= 0)
                return;
            if (listViewProduct.SelectedItems.Count <= 0)
            {
                MessageBox.Show("Bạn chưa chọn mặt hàng");
                return;
            }
            CtrProduct ctrP = new CtrProduct();
            int ret = ctrP.BillDetailsInsert(billID, Convert.ToInt32(listViewProduct.SelectedItems[0].Tag), (double)(numQuantity.Value));
            if (ret > 0)
            {
                RefreshBill();
            }
            else
            {
                if (ret < 0)
                    if (MessageBox.Show("Mặt hàng này đã có trong hóa đơn, bạn muốn thiết lập lại số lượng không?", "Cập nhật số lượng", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        foreach (ListViewItem itemPro in listViewUsedPro.Items)
                        {
                            if (Convert.ToInt32(itemPro.Tag) == -ret)
                            {
                                popupSetQuantity popQuantity = new popupSetQuantity(this, -ret, itemPro.Text, itemPro.SubItems[3].Text, Convert.ToDouble(itemPro.SubItems[1].Tag));
                                popQuantity.ShowDialog();
                            }
                        }
                    }
            }
        }

        private void openTableToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (tableID <= 0)
                return;
            CtrProduct ctrP = new CtrProduct();
            int ret = ctrP.BillInsert(Program.UserEntity.UserID, tableID);
            if (ret > 0)
            {
                CtrAdmin ctra = new CtrAdmin();
                var control1 = (ListView)contextMenuStripOnTable.SourceControl;
                if (control1.SelectedItems.Count > 0)
                    ctra.LogInsert(Program.UserEntity.UserID, Program.UserEntity.UserName, 1, "Mở bàn \"" + control1.SelectedItems[0].Text + "\" (" + tabControl.SelectedTab.Text + ")", "Quản lý dịch vụ");
            }
            if ((ret > 0) || (ret == -1))
            {
                RefreshCurrentTab();
            }
        }

        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RefreshCurrentTab();
        }

        private void cancelBillToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Bạn muốn đóng bàn, hủy đơn hàng này không?", "Xác nhận", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {

                CtrProduct ctrP = new CtrProduct();
                if (ctrP.BillDelete(billID, true) > 0)
                {
                    CtrAdmin ctra = new CtrAdmin();
                    var control1 = (ListView)contextMenuStripOnTable.SourceControl;
                    if (control1.SelectedItems.Count > 0)
                        ctra.LogInsert(Program.UserEntity.UserID, Program.UserEntity.UserName, 3, "Hủy bàn \"" + control1.SelectedItems[0].Text + "\" (" + tabControl.SelectedTab.Text + ")", "Quản lý dịch vụ");
                    RefreshCurrentTab();
                }
            }
        }

        public void RefreshCurrentTab()
        {
            int rangeID = Convert.ToInt32(tabControl.SelectedTab.Name.Substring(7));
            var contls = tabControl.Controls.Find("listViewTableOn" + rangeID, true);
            if (contls.Length > 0)
            {
                try
                {
                    var lv1 = (ListView)contls[0];
                    lv1.Items.Clear();
                    CtrTable ctrT = new CtrTable();
                    var tables = ctrT.TableGetOn(rangeID);
                    foreach (var table in tables)
                    {
                        ListViewItem ListViewItem1 = new ListViewItem(table.TableName);
                        ListViewItem1.ImageIndex = table.BillID.HasValue ? 1 : 0;
                        if (tableID == table.TableID)
                            ListViewItem1.Selected = true;
                        ListViewItem1.Tag = table.TableID.ToString() + "+" + (table.BillID ?? -1).ToString();
                        lv1.Items.Add(ListViewItem1);
                    }
                }
                catch { }
            }
        }

        public void RefreshAndSelectTabOther(int rangeID, int m_tableID)
        {
            int rangeIDCurTab = Convert.ToInt32(tabControl.SelectedTab.Name.Substring(7));
            tableID = m_tableID;
            if (rangeID != rangeIDCurTab)
            {
                var contls = tabControl.Controls.Find("listViewTableOn" + rangeID, true);
                if (contls.Length > 0)
                {
                    try
                    {
                        var lv1 = (ListView)contls[0];
                        lv1.Items.Clear();
                        CtrTable ctrT = new CtrTable();
                        var tables = ctrT.TableGetOn(rangeID);
                        foreach (var table in tables)
                        {
                            ListViewItem ListViewItem1 = new ListViewItem(table.TableName);
                            ListViewItem1.ImageIndex = table.BillID.HasValue ? 1 : 0;
                            if (tableID == table.TableID)
                                ListViewItem1.Selected = true;
                            ListViewItem1.Tag = table.TableID.ToString() + "+" + (table.BillID ?? -1).ToString();
                            lv1.Items.Add(ListViewItem1);
                        }
                    }
                    catch { }
                    try
                    {
                        var tabPs = tabControl.Controls.Find("tabPage" + rangeID, true);
                        if (tabPs.Length > 0)
                        {
                            var tabp = (TabPage)tabPs[0];
                            tabControl.SelectedTab = tabp;
                        }
                    }
                    catch { }

                }
            }
        }
        private void RefreshBill()
        {
            if ((billID <= 0) || (tableID <= 0))
            {
                listViewUsedPro.Items.Clear();
                DisableBillOnTable(true);                
                return;
            }
            DisableBillOnTable(false);
            CtrProduct ctrP = new CtrProduct();
            var items = ctrP.BillDetailsGetByBillID(billID);
            listViewUsedPro.Items.Clear();
            foreach (var item in items)
            {
                var item1 = new ListViewItem(item.ProductName);
                ListViewItem.ListViewSubItem sub1 = new ListViewItem.ListViewSubItem();
                sub1.Text = item.Quantity.ToString();
                sub1.Tag = item.Quantity;
                item1.SubItems.Add(sub1);
                sub1 = new ListViewItem.ListViewSubItem();
                sub1.Text = item.PriceName;
                sub1.Tag = item.Price;
                item1.SubItems.Add(sub1);
                item1.SubItems.Add(item.Unit);
                item1.SubItems.Add(item.Description);
                item1.Tag = item.BillDetailID;
                listViewUsedPro.Items.Add(item1);
            }
            updateTotalMoney();
        }

        private void listViewProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (ListViewItem pro in listViewProduct.Items)
            {
                if (pro.BackColor != Color.Transparent)
                    pro.BackColor = Color.Transparent;
            }
            if (listViewProduct.SelectedItems.Count > 0)
                listViewProduct.SelectedItems[0].BackColor = Color.FromArgb(220, 220, 220);
        }

        public void updateQuantity(int billDetailID, double quantity)
        {
            CtrProduct ctrP = new CtrProduct();
            if (ctrP.BillDetailsUpdateQuantity(billDetailID, quantity) > 0)
            {
                RefreshBill();
            }
        }
        public void updatePrice(int billDetailID, int price)
        {
            CtrProduct ctrP = new CtrProduct();
            if (ctrP.BillDetailsUpdatePrice(billDetailID, price) > 0)
            {
                RefreshBill();
            }
        }
        public void updateDescription(int billDetailID, string des)
        {
            CtrProduct ctrP = new CtrProduct();
            if (ctrP.BillDetailsUpdateDescription(billDetailID, des) > 0)
            {
                RefreshBill();
            }
        }

        private void toolStripButtonSetQuantity_Click(object sender, EventArgs e)
        {
            showPopupSetQuantity();
        }
        private void listViewUsedPro_DoubleClick(object sender, EventArgs e)
        {
            showPopupSetQuantity();
        }

        private void showPopupSetQuantity()
        {
            if (listViewUsedPro.SelectedItems.Count <= 0)
                return;
            var itemPro = listViewUsedPro.SelectedItems[0];
            popupSetQuantity popQuantity = new popupSetQuantity(this, Convert.ToInt32(itemPro.Tag), itemPro.Text, itemPro.SubItems[3].Text, Convert.ToDouble(itemPro.SubItems[1].Tag));
            popQuantity.ShowDialog();
        }

        private void toolStripButtonChangePrice_Click(object sender, EventArgs e)
        {
            if (!Program.IsActive)
            {
                MessageBox.Show("Bạn cần đăng ký sử dụng phần mềm để sử dụng chức năng này!", "Thông báo");
                return;
            }
            if (listViewUsedPro.SelectedItems.Count <= 0)
                return;
            var itemPro = listViewUsedPro.SelectedItems[0];
            popupSetPrice popPrice = new popupSetPrice(this, Convert.ToInt32(itemPro.Tag), itemPro.Text, Convert.ToInt32(itemPro.SubItems[2].Tag));
            popPrice.ShowDialog();
        }

        private void toolStripButtonUpdateDescription_Click(object sender, EventArgs e)
        {
            if (!Program.IsActive)
            {
                MessageBox.Show("Bạn cần đăng ký sử dụng phần mềm để sử dụng chức năng này!", "Thông báo");
                return;
            }
            if (listViewUsedPro.SelectedItems.Count <= 0)
                return;
            var itemPro = listViewUsedPro.SelectedItems[0];
            popupSetDescription popDes = new popupSetDescription(this, Convert.ToInt32(itemPro.Tag), itemPro.Text, itemPro.SubItems[3].Text, itemPro.SubItems[1].Text, itemPro.SubItems[2].Text, itemPro.SubItems[4].Text);
            popDes.ShowDialog();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (listViewUsedPro.SelectedItems.Count <= 0)
                return;
            var itemPro = listViewUsedPro.SelectedItems[0];
            if (MessageBox.Show("Bạn có chắc chắn muốn xóa \"" + itemPro.Text + "\" khỏi đơn hàng?", "Xác nhận", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                CtrProduct ctrP = new CtrProduct();
                if (ctrP.BillDetailsDelete(Convert.ToInt32(itemPro.Tag)) > 0)
                {
                    RefreshBill();
                }
            }
        }

        private void updateTotalMoney()
        {
            if (billID > 0)
            {
                CtrProduct ctrP = new CtrProduct();
                var m_price = ctrP.BillGetPriceOther(billID);
                lblSumMoney.Text = m_price.SumMoney==0?"0 VNĐ":m_price.SumMoney.ToString("0,0") + " VNĐ";
                numService.Value = m_price.PriceServices;
                numericPromotion.Value = m_price.PromotionMoney;
                lblTotalMoney.Text = m_price.TotalMoney==0?"0 VNĐ":m_price.TotalMoney.ToString("0,0") + " VNĐ";
            }
            else
            {
                lblSumMoney.Text = "0 VNĐ";
                numService.Value = 0;
                numericPromotion.Value = 0;
                lblTotalMoney.Text = "0 VNĐ";
            }
        }
        private void numService_ValueChanged(object sender, EventArgs e)
        {
            int ser = Convert.ToInt32(numService.Value);
            numService.Value = ser;
            CtrProduct ctrP = new CtrProduct();
            ctrP.BillUpdatePriceServices(billID, ser);

            updateTotalMoney();
        }

        private void numericPromotion_ValueChanged(object sender, EventArgs e)
        {
            int prom = Convert.ToInt32(numericPromotion.Value);
            numericPromotion.Value = prom;
            CtrProduct ctrP = new CtrProduct();
            int ret = ctrP.BillUpdatePromotionMoney(billID, prom);
            if (ret < 0)
            {
                MessageBox.Show("Số tiền giảm giá không hợp lệ", "Cảnh báo");
                numericPromotion.Value = -ret;
            }
            else
                updateTotalMoney();
        }


        private void btnPayment_Click(object sender, EventArgs e)
        {
            bool m_show = false;
            popupPayment pay = new popupPayment(this, billID, ref m_show, (permission & (int)Config.Enum.Permission.Add) == (int)Config.Enum.Permission.Add);
            if (m_show)
                pay.ShowDialog();
        }

        private void paymentToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (btnPayment.Enabled)
                btnPayment.PerformClick();
        }

        private void listViewProduct_DoubleClick(object sender, EventArgs e)
        {
            if (btnAdd.Enabled)
                btnAdd.PerformClick();
        }

        private void grossToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!Program.IsActive)
            {
                MessageBox.Show("Bạn cần đăng ký sử dụng phần mềm để sử dụng chức năng này!", "Thông báo");
                return;
            }
            var control1 = (ListView)contextMenuStripOnTable.SourceControl;
            string tableFrom = "";
            if (control1.SelectedItems.Count > 0)
                tableFrom = "\"" + control1.SelectedItems[0].Text + "\" (" + tabControl.SelectedTab.Text + ")";

            popupChangeTable popMove = new popupChangeTable(this, billID, tableFrom, 1);
            popMove.ShowDialog();
        }

        private void moveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!Program.IsActive)
            {
                MessageBox.Show("Bạn cần đăng ký sử dụng phần mềm để sử dụng chức năng này!", "Thông báo");
                return;
            }
            var control1 = (ListView)contextMenuStripOnTable.SourceControl;
            string tableFrom = "";
            if (control1.SelectedItems.Count > 0)
                tableFrom = "\"" + control1.SelectedItems[0].Text + "\" (" + tabControl.SelectedTab.Text + ")";
            popupChangeTable popMove = new popupChangeTable(this, billID, tableFrom, 2);
            popMove.ShowDialog();
        }

        private void tabControl_SelectedIndexChanged(object sender, EventArgs e)
        {
            RefreshCurrentTab();
        }
        private void DisableBillOnTable(bool isDisable)
        {
            numService.Enabled = !isDisable;
            numericPromotion.Enabled = !isDisable;
            btnPayment.Enabled = !isDisable;
            btnAdd.Enabled = !isDisable;
            btnDelete.Enabled = !isDisable;
        }

    }
}
